<template>
  <el-card shadow="hover">
    <el-descriptions
      class="margin-top"
      title="合同收款总额（元）"
      :column="3"
      :size="size"
      border
    />
    <div style="padding-bottom: 10px">
      <el-table v-loading="listLoading" :data="PaymentList" show-summary>
        <el-table-column
          align="center"
          label="收款ID"
          prop="PaymentID"
          show-overflow-tooltip
          fixed
          width="80"
        />
        <el-table-column align="center" label="款项类型" width="80">
          <template #default="{ row }">
            <el-text>{{ row.PaymentClassName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款日期" width="120">
          <template #default="{ row }">
            <el-text>{{ row.PaymentDate }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款方式" width="80">
          <template #default="{ row }">
            <el-text>{{ row.PaymentTypeName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款公司">
          <template #default="{ row }">
            <el-text>{{ row.PaymentCompanyName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款人">
          <template #default="{ row }">
            <el-text>{{ row.SaleStaffName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款账户" width="140">
          <template #default="{ row }">
            <el-text>{{ row.PaymentAccount }}</el-text>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="PaymentMoney"
          label="到账金额"
          width="100"
        />
        <el-table-column
          align="center"
          prop="PaymentCost"
          label="成本金额"
          width="90"
        />
        <el-table-column
          align="center"
          prop="HesuanMoney"
          label="业绩核算金额"
          width="110"
        />
        <el-table-column
          align="center"
          prop="HesuanOrderCount"
          label="业绩核算单量"
          width="110"
        />
        <el-table-column
          v-if="OrderFlowState === 1"
          align="center"
          label="操作"
          width="150"
        >
          <template #default="{ row }">
            <el-button type="success" size="small" @click="paymentEdit(row)">
              修改
            </el-button>
            <el-button type="danger" size="small" @click="paymentDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="PaymentMemo"
          label="备注"
          width="110"
        />
        <el-table-column align="center" label="附件" width="80">
          <template #default="{ row }">
            <el-button
              v-if="JSON.parse(row.PaymentAttFiles).length"
              type="success"
              size="small"
              @click="NewUploadFile(row)"
            >
              附件
            </el-button>
            <el-button
              v-else
              type="danger"
              size="small"
              @click="NewUploadFile(row)"
            >
              附件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="OrderFlowState === 2 && pageflow === 3"
          align="center"
          label="确认收款"
          fixed="right"
          width="145"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.PaymentState == 0"
              type="danger"
              size="small"
              @click="paymentConfirm(row)"
            >
              收款确认
            </el-button>
            <el-button v-else type="success" size="small">
              {{ row.PaymentStaffName }}已确认收款
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-else
          align="center"
          label="确认收款"
          fixed="right"
          width="145"
        >
          <template #default="{ row }">
            <el-button
              v-if="row.PaymentState == 0 && pageflow == 3"
              type="danger"
              size="small"
              plain
              @click="paymentConfirm(row)"
            >
              收款确认
            </el-button>
            <el-button
              v-else-if="row.PaymentState == 0 && pageflow != 3"
              type="danger"
              size="small"
              plain
            >
              待收款确认
            </el-button>
            <el-button v-else type="success" size="small" plain>
              {{ row.PaymentStaffName }}已确认收款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <vab-query-form
      v-if="OrderFlowState === 1 || OrderFenqi === 1"
      style="padding: 10px"
    >
      <vab-query-form-right-panel :span="22">
        <el-form ref="formRef" :model="PaymentForm" :rules="rules">
          <el-space>
            <el-form-item label="款项类型" prop="PaymentClass">
              <el-select
                v-model="PaymentForm.PaymentClass"
                placeholder=""
                style="width: 150px"
              >
                <el-option
                  v-for="(item, index) in PaymentOptions.PaymentClass"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="到账日期" prop="PaymentDate">
              <el-date-picker
                v-model="PaymentForm.PaymentDate"
                type="date"
                placeholder="到账日期"
              />
            </el-form-item>
            <el-form-item label="收款方式" prop="PaymentType">
              <el-select
                v-model="PaymentForm.PaymentType"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="(item, index) in PaymentOptions.PaymentTypes"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="收款公司" prop="PaymentCompany">
              <el-cascader
                v-model="PaymentForm.PaymentCompany"
                :options="PaymentOptions.PaymentCompanys"
                :props="companyProps"
                @change="handleChange"
              />
              <!-- <el-select
                v-model="PaymentForm.PaymentCompany"
                placeholder="请选择收款公司"
                style="width: 250px"
              >
                <el-option
                  v-for="(item, index) in PaymentOptions.PaymentCompanys"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select> -->
            </el-form-item>
            <!-- <el-form-item label="选择收款账户">
            <el-select
              v-model="PaymentForm.PaymentAccount"
              placeholder="选择收款账户"
              style="width: 150px"
            >
              <el-option :value="1" label="现金" />
              <el-option :value="2" label="保定银行(25354235)" />
              <el-option :value="3" label="工商银行(90852904)" />
            </el-select>
          </el-form-item> -->
          </el-space>
          <el-space>
            <el-form-item label="到账金额" prop="PaymentMoney">
              <!-- <el-input-number
                v-model="PaymentForm.PaymentMoney"
                precision="2"
                :step="100"
                @input="moneyChange"
              /> -->
              <el-input
                v-model="PaymentForm.PaymentMoney"
                type="number"
                style="width: 110px"
                @input="moneyChange"
              />
            </el-form-item>
            <el-form-item label="成本金额" prop="PaymentCost">
              <!-- <el-input-number
                v-model="PaymentForm.PaymentCost"
                precision="2"
                :step="100"
                @input="moneyChange"
              /> -->
              <el-input
                v-model="PaymentForm.PaymentCost"
                type="number"
                style="width: 110px"
                disabled
                @input="moneyChange"
              />
            </el-form-item>
            <el-form-item label="业绩核算金额" prop="HesuanMoney">
              <!-- <el-input-number
                v-model="PaymentForm.HesuanMoney"
                precision="2"
                :step="100"
              /> -->
              <el-input
                v-model="PaymentForm.HesuanMoney"
                type="number"
                disabled
                style="width: 110px"
              />
            </el-form-item>
            <el-form-item label="业绩核算单量" prop="HesuanOrderCount">
              <el-input-number
                v-model="PaymentForm.HesuanOrderCount"
                precision="2"
                :step="0.1"
              />
            </el-form-item>
          </el-space>
          <el-space>
            <el-form-item label="备注">
              <el-input
                v-model="PaymentForm.PaymentMemo"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                :type="
                  PaymentForm?.PaymentAttFiles?.length != 0
                    ? 'success'
                    : 'primary'
                "
                @click="uploadFile"
              >
                附件
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="savePayment()">
                {{ PaymentForm.PaymentID == 0 ? '确认添加' : '确认修改' }}
              </el-button>
            </el-form-item>
          </el-space>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>
  </el-card>
  <!-- 保存后点击上传附件 -->
  <el-dialog v-model="NewAttach" title="上传附件" @close="attachClose">
    <el-upload
      :file-list="clickPaymentAttFiles"
      :multiple="true"
      action="https://api.sanjianke.com/common/Upload/upload?file=PaymentList&type=image"
      list-type="picture-card"
      :on-preview="NewPreview"
      :on-remove="NewRemove"
      :on-success="NewSuccess"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="upAttachment">保存</el-button>
      </div>
    </template>
    <!-- <el-dialog v-model="dialogVisible" top="3vh">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
        style="width: 100%"
      />
    </el-dialog> -->
  </el-dialog>
  <!-- 添加时上传附件 -->
  <el-dialog v-model="dialogOrderAttach" title="上传附件">
    <el-upload
      :file-list="PaymentForm.PaymentAttFiles"
      :multiple="true"
      action="https://api.sanjianke.com/common/Upload/upload?file=PaymentList&type=image"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleAvatarSuccess"
      accept="image/png, image/jpeg"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button @click="noUpFiles">清除</el-button> -->
        <el-button type="primary" @click="dialogOrderAttach = false">
          确定
        </el-button>
      </div>
    </template>
    <!-- <el-dialog v-model="dialogVisible" top="3vh">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image"
        style="width: 100%"
      />
    </el-dialog> -->
  </el-dialog>
  <!-- 点击收款确认后弹dialog 展示 -->
  <el-dialog
    v-model="dialogCollect"
    title="合同收款信息"
    width="800px"
    top="3vh"
    @close="collectClose"
  >
    <el-form ref="formRef" label-width="130px" :model="confirmMsg">
      <el-form-item label="款项类型">
        <el-input v-model="confirmMsg.PaymentClassName" disabled />
      </el-form-item>
      <el-form-item label="收款日期">
        <el-input v-model="confirmMsg.PaymentDate" disabled />
      </el-form-item>
      <el-form-item label="收款方式">
        <el-input v-model="confirmMsg.PaymentTypeName" disabled />
      </el-form-item>
      <el-form-item label="收款公司">
        <el-input v-model="confirmMsg.PaymentCompanyName" disabled />
      </el-form-item>
      <el-form-item label="收款账户">
        <el-input v-model="confirmMsg.PaymentAccount" disabled />
      </el-form-item>
      <el-form-item label="到账金额">
        <el-input v-model="confirmMsg.PaymentMoney" disabled />
      </el-form-item>
      <el-form-item label="成本金额">
        <el-input v-model="confirmMsg.PaymentCost" disabled />
      </el-form-item>
      <el-form-item label="业绩核算金额">
        <el-input v-model="confirmMsg.HesuanMoney" disabled />
      </el-form-item>
      <el-form-item label="业绩核算单量">
        <el-input v-model="confirmMsg.HesuanOrderCount" disabled />
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="confirmMsg.PaymentMemo" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="collectClose">关 闭</el-button>
      <el-button
        v-if="confirmMsg.PaymentState == 0 && actConfirm"
        type="primary"
        @click="confirmPayment(confirmMsg)"
      >
        确定收款
      </el-button>
    </template>
  </el-dialog>
  <el-image-viewer
    v-if="dialogVisible"
    :url-list="[dialogImageUrl]"
    @close="closeViewer"
  />
</template>

<script>
  import { getPaymentOptions } from '@/api/common'
  import { savePayments, modPaymentFile } from '@/api/businessOrderCreate'

  export default defineComponent({
    name: 'PaymentList',
    props: {
      pageflow: {
        type: Number,
        default: 0,
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        companyProps: {
          expandTrigger: 'hover',
        },
        orPayment: false,
        NewAttach: false,
        dialogfujian: false,
        confirmMsg: {},
        actConfirm: 0,
        dialogCollect: false,
        dialogVisible: false,
        clickPaymentID: 0,
        clickPaymentAttFiles: [],
        dialogImageUrl: '',
        fileList: [],
        dialogOrderAttach: false,
        ProductList: [],
        GiftList: [],
        OrderID: 0,
        OrderFlowState: 1,
        listLoading: false,
        PaymentOptions: {
          PaymentClass: [],
          PaymentTypes: [],
          PaymentCompanys: [],
        },
        formRef: null,
        editRef: null,
        PaymentList: [],
        OrderFenqi: 0,
        PaymentForm: {
          PaymentAttFiles: [],
          OrderID: 0,
          PaymentClass: 1,
          saveType: 0,
        },
        rules: {
          PaymentClass: [
            { required: true, trigger: 'change', message: '请选择款项类型' },
          ],
          PaymentDate: [
            {
              required: true,
              trigger: 'change',
              message: '请务必填写服务期限',
            },
          ],

          PaymentCost: [
            {
              required: true,
              trigger: 'change',
              message: '请输入成本金额',
            },
          ],
          PaymentType: [
            {
              required: true,
              trigger: 'change',
              message: '请选择收款方式',
            },
          ],
          PaymentCompany: [
            { required: true, trigger: 'change', message: '请选择收款公司' },
          ],
          PaymentMoney: [
            { required: true, trigger: 'change', message: '请填写到账金额' },
          ],
          HesuanMoney: [
            {
              required: true,
              trigger: 'change',
              message: '请填写业绩核算金额',
            },
          ],
          HesuanOrderCount: [
            {
              required: true,
              trigger: 'change',
              message: '请填写业绩核算单量',
            },
          ],
        },
        title: '',
      })
      const noUpFiles = () => {
        state.dialogOrderAttach = false
        state.PaymentForm.PaymentAttFiles = []
      }
      const showList = async (OrderInfo, list, ProductList, GiftList) => {
        state.PaymentForm.HesuanOrderCount = 1
        // state.ProductList = ProductList
        // state.GiftList = GiftList

        if (ProductList) {
          // 获取成本金额
          await getPaymentCost(ProductList, GiftList, list)
          // 获取到账金额
          await amountReceived(ProductList, list)
          // 获取业绩核算金额
          await moneyChange()
        }

        console.log(GiftList, '1')
        console.log(list, '2')
        console.log(ProductList, '3')

        state.OrderID = OrderInfo.OrderID
        state.OrderFenqi = OrderInfo.OrderFenqi
        state.OrderFlowState = Math.abs(OrderInfo.OrderFlowState)
        console.log(OrderInfo, 'OrderInfo收款')
        state.PaymentForm.OrderID = OrderInfo.OrderID
        state.PaymentForm.PaymentID = 0
        state.PaymentList = list
        console.log(state.PaymentList, ' PaymentState!')
      }
      const paymentEdit = (row) => {
        console.log(row, '修改！！')
        state.PaymentForm = row
        if (typeof row.PaymentAttFiles == 'string') {
          state.PaymentForm.PaymentAttFiles = JSON.parse(row.PaymentAttFiles)
        } else {
          state.PaymentForm.PaymentAttFiles = row.PaymentAttFiles
        }
      }

      const paymentConfirm = (row) => {
        console.log(row)
        // state.dialogCollect = true
        // state.actConfirm = act
        state.confirmMsg = row

        if (row.PaymentID) {
          $baseConfirm('你确认收到了款项吗', null, async () => {
            const { msg } = await savePayments({
              PaymentID: row.PaymentID,
              PaymentState: 1,
              saveType: 2,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }

      const paymentDelete = (row) => {
        console.log(row)
        if (row.PaymentID) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await savePayments({
              PaymentID: row.PaymentID,
              delok: 1,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
          })
        }
      }
      const savePayment = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            state.PaymentForm.saveType = 1
            const { msg } = await savePayments(state.PaymentForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            state['formRef'].resetFields()
            state.PaymentForm = {
              PaymentAttFiles: [],
              OrderID: 0,
              PaymentClass: 1,
              saveType: 0,
            }
            emit('fetch-data')
          }
        })
      }
      const getOptions = async () => {
        state.listLoading = true

        const {
          data: { PaymentClass, PaymentTypes, PaymentCompanys },
        } = await getPaymentOptions()
        state.PaymentOptions.PaymentClass = PaymentClass
        state.PaymentOptions.PaymentTypes = PaymentTypes
        state.PaymentOptions.PaymentCompanys = PaymentCompanys
        state.listLoading = false
      }
      // 获得成本金额
      const getPaymentCost = async (ProductList, GiftList, list) => {
        let ProductCost = 0
        let GiftCost = 0
        let collection = 0
        // 产品总成本
        await ProductList.forEach((item) => {
          ProductCost += Number(item.ProductCost)
        })
        // 礼物总成本
        await GiftList.forEach((item) => {
          GiftCost += Number(item.ProductCost)
        })
        // 已收款的成本
        await list.forEach((item) => {
          collection += Number(item.PaymentCost)
        })

        // 待收成本
        state.PaymentForm.PaymentCost = ProductCost + GiftCost - collection

        console.log(
          state.PaymentForm.PaymentCost,
          ProductCost,
          GiftCost,
          collection
        )
      }
      // 获取到账金额
      const amountReceived = async (ProductList, list) => {
        let ProductCost = 0
        let collection = 0
        // 产品总金额
        await ProductList.forEach((item) => {
          ProductCost += Number(item.ProductMoney)
        })
        // 已收款总金额
        await list.forEach((item) => {
          collection += Number(item.PaymentMoney)
        })
        // 待收总金额
        state.PaymentForm.PaymentMoney = ProductCost - collection
      }
      const closeViewer = () => {
        state.dialogImageUrl = ''
        state.dialogVisible = false
      }
      const handlePictureCardPreview = (uploadFile) => {
        state.dialogImageUrl = uploadFile.url
        state.dialogVisible = true
      }
      const uploadFile = () => {
        state.dialogOrderAttach = true
      }

      const handleAvatarSuccess = (response) => {
        const data = {
          url: response.data.url,
        }
        state.PaymentForm.PaymentAttFiles.push(data)
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
      }
      const confirmPayment = (row) => {
        if (row.PaymentID) {
          $baseConfirm('你确认收到了款项吗', null, async () => {
            const { msg } = await savePayments({
              PaymentID: row.PaymentID,
              PaymentState: 1,
              saveType: 2,
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            collectClose()
            emit('fetch-data')
          })
        }
      }
      const collectClose = () => {
        state.dialogCollect = false
        state.confirmMsg = {}
      }

      onMounted(() => {
        getOptions()
      })

      // 到账金额或者成本金额变化时
      const moneyChange = () => {
        state.PaymentForm.HesuanMoney =
          Number(state.PaymentForm.PaymentMoney) -
          Number(state.PaymentForm.PaymentCost)
      }

      const handleRemove = () => {
        // const index = state.PaymentForm.PaymentAttFiles.findIndex(
        //   (fileItem) => {
        //     console.log(fileItem.url, row.url)
        //     return fileItem.url === row.url
        //   }
        // )
        console.log(state.PaymentForm.PaymentAttFiles)
        // state.PaymentForm.PaymentAttFiles.splice(index, 1)
      }

      const NewUploadFile = (row) => {
        // 点击附件后判断是否已经确认收款  确认收款后不能进行添加删除
        if (row.PaymentState) {
          state.orPayment = true
        } else {
          state.orPayment = false
        }
        state.NewAttach = true
        if (row) {
          state.clickPaymentID = row.PaymentID
        }
        if (typeof row.PaymentAttFiles == 'string') {
          state.clickPaymentAttFiles = JSON.parse(row.PaymentAttFiles)
        } else {
          state.clickPaymentAttFiles = row.PaymentAttFiles
        }
      }

      // 点击附件后保存附件
      const upAttachment = async () => {
        const dataMsg = {
          PaymentID: state.clickPaymentID,
          PaymentAttFiles: state.clickPaymentAttFiles,
        }
        await modPaymentFile(dataMsg)
        attachClose()
        emit('fetch-data')
        console.log('点击附件后可以直接修改附件')
      }
      const attachClose = () => {
        state.NewAttach = false
        state.clickPaymentID = 0
        state.clickPaymentAttFiles = []
      }

      const NewRemove = () => {
        if (state.OrderFlowState != 1) {
          ElMessage({
            message: '不可删除',
            type: 'warning',
            plain: true,
          })
          state.NewAttach = false
          return
        }

        console.log(state.clickPaymentAttFiles, '222')
      }

      const NewPreview = (uploadFile) => {
        state.dialogImageUrl = uploadFile.url
        state.dialogVisible = true
      }

      const NewSuccess = (response) => {
        const data = {
          url: response.data.url,
        }
        state.clickPaymentAttFiles.push(data)
        console.log(state.clickPaymentAttFiles, 'clickPaymentAttFiles')

        ElMessage({
          message: '上传成功',
          type: 'success',
        })
      }

      const handleChange = (value) => {
        console.log(value, 'handleChange')
      }

      return {
        ...toRefs(state),
        showList,
        moneyChange,
        handleChange,
        NewRemove,
        getPaymentCost,
        NewUploadFile,
        NewPreview,
        upAttachment,
        attachClose,
        collectClose,
        handleRemove,
        confirmPayment,
        handleAvatarSuccess,
        uploadFile,
        NewSuccess,
        noUpFiles,
        handlePictureCardPreview,
        amountReceived,
        savePayment,
        paymentDelete,
        paymentConfirm,
        paymentEdit,
        closeViewer,
      }
    },
  })
</script>
<style scoped>
  :deep(.el-image-viewer__canvas) {
    transform: scale(0.6) rotate(0deg);
  }
</style>
